package com.css.fxfzysx.util.hypergraph.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.base.dict.repository.DictItemRepository;
import com.css.fxfzysx.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.constants.YNEnum;
import com.css.fxfzysx.util.*;
import com.css.fxfzysx.util.hypergraph.entity.NetworkanalystVersion;
import com.css.fxfzysx.util.hypergraph.service.HypergraphService;
import com.css.fxfzysx.zcpt.sys.entity.SUser;
import com.css.fxfzysx.zcpt.sys.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HypergraphServiceImpl implements HypergraphService {

    @Value("${hypergraph.iServerHttp}")
    String iServerHttp;
    @Value("${hypergraph.iServerHttp10i}")
    String iServerHttp10i;
    @Value("${hypergraph.userName}")
    String userName;
    @Value("${hypergraph.password}")
    String password;
    RestTemplate restTemplate = getRestTemplate();

    @Value("${hypergraph.filePath}")
    String filePath;
    @Value("${hypergraph.mapsPath}")
    String mapsPath;

    @Autowired
    DictItemRepository dictItemRepository;
    @Autowired
    SUserService sUserService;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    /**
     * 调度器使用的RestTemplate，超时6000s
     * @return
     */
    public RestTemplate getRestTemplate(){
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(6000))
                .setReadTimeout(Duration.ofSeconds(6000))
                .build();
        //解决中文乱码
        List<HttpMessageConverter<?>> msgConv = restTemplate.getMessageConverters();
        if(msgConv != null && !msgConv.isEmpty()) {
            for(int i = 0; i < msgConv.size(); i++ ){
                if(msgConv.get(i).getClass().equals(StringHttpMessageConverter.class)) {
                    msgConv.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
                }
            }
        }
        return restTemplate;
    }

    /**
     * @param map layerName:
     *            type://类型
     *            WorkspaceReload//刷新指定超图工作空间数据源数据集
     *            exportShp//导出shp文件
     *            newWorkspaceNetwork//工作空间发布交通网络分析服务
     *            deleteWorkspace//删除超图工作空间服务
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse getServerToken(Map<String, Object> map) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/security/tokens.rjson";
            String queryType = (String) map.get("type");
            if(queryType.equals("newWorkspaceNetwork") || queryType.equals("deleteWorkspace")){//10i试用版网络分析服务
                dataUrl = iServerHttp10i + "/iserver/services/security/tokens.rjson";
            }
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userName);
            jsonObject.put("password", password);
            jsonObject.put("clientType", "NONE");//查询数量
            jsonObject.put("expiration", 600);//申请令牌的有效期，从发布令牌的时间开始计算，单位为分钟
            //System.out.println(jsonObject);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);

            // result.put("result", exchange.getBody());

            String type = (String) map.get("type");
            String layerName = (String) map.get("layerName");
            if (type.equals("WorkspaceReload")) {
                String datasource = (String) map.get("datasource");//数据源
                String dataset = (String) map.get("dataset");//数据集
                //查询字典--超图数据源工作空间文件路径
                DictItemEntity dte = dictItemRepository.findOneByDictItemCodeAndDictId(datasource, "12");
                String smwuUrl = dte.getDictItemName();//工作空间文件路径
                //刷新指定超图工作空间数据源数据集
                restResponse = mapLayerWorkspaceReload(smwuUrl, datasource, dataset, exchange.getBody());
            } else if (type.equals("token")) {//获取超图服务token
                String token = exchange.getBody();
                restResponse = RestResponse.succeed(token);
            } else if (type.equals("exportShp")) {
                String sqlFilter = (String) map.get("sqlFilter");//过滤条件
                String timeStamp = (String) map.get("timeStamp");//时间戳，用于数据集导出名称后缀，防止重名
                String datasource = (String) map.get("datasource");//数据源fxfzfxqh
                //tif发布超图服务工具--创建任务（导出shp文件）
                restResponse = tifMapLayerToolJobPost(datasource, layerName, sqlFilter, timeStamp, exchange.getBody());
            } else if(type.equals("newWorkspaceNetwork")){//工作空间发布交通网络分析服务
                //工作空间发布交通网络分析服务
                restResponse = supermapPostWorkspace(map,exchange.getBody());
            } else if(type.equals("deleteWorkspace")){//删除超图工作空间服务
                NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
                //根据ID逻辑删除版本
                deleteNetworkanalystVersionById(networkanalystVersion.getId());
                //删除超图工作空间服务
                restResponse = supermapDeleteWorkspace(map,exchange.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean getWorkspaceReload(String dataset) {
        boolean bool = false;
        Map<String, Object> map = new HashMap<>();
        map.put("type", "WorkspaceReload");
        map.put("datasource", "fxfzczt");//数据源（数据库名）
        map.put("dataset", dataset);//数据集（表名）
        RestResponse restResponse1 = getServerToken(map);//刷新指定超图工作空间数据源数据集
        if (restResponse1.getCode() == 200) {
            //刷新成功
            bool = true;
        }

        return bool;
    }

    // tif发布超图服务工具--创建任务（导出shp文件）
    private RestResponse tifMapLayerToolJobPost(String datasource, String layerName,String sqlFilter,String timeStamp,String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/sps.WorkflowProcessFactory.models.tif发布:导出shp文件fxqh/jobs?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);
            String resultFilePath = filePath + layerName + "_" + timeStamp + ".file";//导出文件路径
            //过滤条件
            String sql = "1=1";
            if (!PlatformObjectUtils.isEmpty(sqlFilter)) {
                sql = sqlFilter;
                //随机数
                String random1 = String.valueOf(Math.round(Math.random() * 10));
                String random2 = String.valueOf(Math.round(Math.random() * 10));
                String random3 = String.valueOf(Math.round(Math.random() * 10));
                resultFilePath = filePath + layerName + "_" + timeStamp + random1 + random2 + random3 + ".file";//导出文件路径
            }
            //执行处理自动化工具时的参数设置，形式为{”ParameterID1”:”value1”,”ParameterID2”:”value2”,……}，其中ParameterID为工具的参数ID，由对应的处理自动化工具描述可以确定，value为参数的值
            JSONObject jsonObject = new JSONObject();
            JSONObject parameter = new JSONObject();
            parameter.put("String_1", layerName);//数据集名称（表名）
            parameter.put("String_2", resultFilePath);//导出文件路径
            parameter.put("String_3", sql);//过滤条件
            jsonObject.put("parameter", parameter);
            JSONArray environment = new JSONArray();
            jsonObject.put("environment", environment);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            // result.put("result", body.getString("jobID"));

            restResponse = tifMapLayerToolJobGet(body.getString("jobID"), serverToken);
            if (restResponse.getCode() == 200) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("dataset", layerName);
                jsonObject1.put("resultFilePath", resultFilePath);
                restResponse.setData(jsonObject1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    private RestResponse tifMapLayerToolJobGet(String jobID, String serverToken) {
        JSONObject result = new JSONObject();
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/jobs/" + jobID + ".json?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            if (!body.getJSONObject("state").getBooleanValue("success")
                    && !body.getJSONObject("state").getString("runState").equals("RUNNING")) {
                return RestResponse.fail("未获取到数据！");
            }
            BigDecimal percent = body.getJSONObject("progress").getBigDecimal("percent");
            while (percent.compareTo(BigDecimal.valueOf(100)) < 0) {
                Thread.sleep(500);
                //获取任务执行百分比
                percent = tifMapLayerToolJobGetPercent(jobID, serverToken);
                if (percent.compareTo(BigDecimal.valueOf(-1)) == 0) {
                    return RestResponse.fail("该任务未获取到数据！");
                }
            }
            result.put("result", "获取成功！");
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("无效的令牌")){
                return RestResponse.fail("无效的令牌！");
            }
            tifMapLayerToolJobGet(jobID, serverToken);
        }
        return RestResponse.succeed(result);
    }

    //获取任务执行百分比
    private BigDecimal tifMapLayerToolJobGetPercent(String jobID, String serverToken) {
        BigDecimal jobPercent = BigDecimal.ZERO;
        try {
            String dataUrl = iServerHttp + "/iserver/services/geoprocessing/restjsr/gp/v2/jobs/" + jobID + ".json?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return jobPercent;
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(new JSONObject(), headers);
            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, JSONObject.class);
            JSONObject body = exchange.getBody();
            if (body == null) {
                return jobPercent;
            }
            if (!body.getJSONObject("state").getBooleanValue("success")
                    && !body.getJSONObject("state").getString("runState").equals("RUNNING")) {
                return BigDecimal.valueOf(-1);
            }
            BigDecimal percent = body.getJSONObject("progress").getBigDecimal("percent");
            if(percent.compareTo(BigDecimal.valueOf(100)) == 0){
                if(body.getJSONObject("state").getString("runState").equals("RUNNING")){//正在执行
                    percent = BigDecimal.valueOf(99);
                }
            }
            jobPercent = percent;
        } catch (Exception e) {
            e.printStackTrace();
            if(e.getMessage().contains("无效的令牌")){
                return BigDecimal.valueOf(-1);
            }
            return jobPercent;
        }
        return jobPercent;
    }

    //刷新指定超图工作空间数据源数据集
    private RestResponse mapLayerWorkspaceReload(String smwuUrl, String datasource, String dataset, String serverToken) {
        RestResponse restResponse = null;
        try {
            String dataUrl = iServerHttp + "/iserver/manager/workspaces/workspacereload.rjson?token=" + serverToken;
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //刷新指定数据源数据集时的参数设置，形式为{"workspaceConnectionInfo":"C:/Users/lenovo/Desktop/192/MapData/fxfzfxqh/fxfzdzzh10/fxfzfxqh.smwu","isForce":true,"datasets":{"fxfzfxqh":["dzzh_slide_result_intensity"]}}
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("workspaceConnectionInfo", smwuUrl);
            jsonObject.put("isForce", true);
            JSONObject datasets = new JSONObject();
            JSONArray datasetArray = new JSONArray();
            datasetArray.add(dataset);
            datasets.put(datasource, datasetArray);//数据源数据集名称
            jsonObject.put("datasets", datasets);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject, headers);
            ResponseEntity<String> exchange1 = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
//            ResponseEntity<JSONObject> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, JSONObject.class);
            JSONObject body = JSON.parseObject(exchange1.getBody());
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            if (body.getBooleanValue("succeed")) {
                restResponse = RestResponse.succeed("刷新成功");
            } else {
                restResponse = RestResponse.fail("刷新失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }
    //工作空间发布交通网络分析服务
    private RestResponse supermapPostWorkspace(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            String datasource = networkanalystVersion.getDatasource();//数据源名称
            String dataset = networkanalystVersion.getDataset();//工作空间内的网络数据集名称
            if (PlatformObjectUtils.isEmpty(smwuUrl) || PlatformObjectUtils.isEmpty(udbxUrl) || PlatformObjectUtils.isEmpty(datasource) || PlatformObjectUtils.isEmpty(dataset)){
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //发布工作空间
//            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            String dataUrl = iServerHttp10i + "/iserver/manager/workspaces.rjson?token=" + serverToken;//10i试用版网络分析服务
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息
            JSONArray servicesTypes = new JSONArray();
            //地图服务
            servicesTypes.add("RESTMAP");//地图服务
            parameter.put("mapEditable", true);
            parameter.put("mapDpi", 96);
            //交通网络分析服务
            servicesTypes.add("RESTTRANSPORTATIONANALYST");//交通网络分析服务
            parameter.put("servicesTypes", servicesTypes);//发布的服务类型
            parameter.put("isMultiInstance", false);//是否启用多实例
            parameter.put("instanceCount", "");
            JSONObject transportationAnalystSetting = new JSONObject();
            JSONArray weightFieldInfos = new JSONArray();
            JSONObject weightFieldInfo = new JSONObject();
            weightFieldInfo.put("backWeightField", "SmLength");
            weightFieldInfo.put("forwardWeightField", "SmLength");
            weightFieldInfo.put("name", "SmLength");
            weightFieldInfos.add(weightFieldInfo);//权值字段信息集合，必设参数。
            transportationAnalystSetting.put("weightFieldInfos", weightFieldInfos);
            transportationAnalystSetting.put("workspaceConnectString", smwuUrl);
            transportationAnalystSetting.put("datasourceName", datasource);
            transportationAnalystSetting.put("datasetName", dataset);
            transportationAnalystSetting.put("nodeIDField", "SmNodeID");
            transportationAnalystSetting.put("edgeIDField", "SmEdgeID");
            transportationAnalystSetting.put("fromNodeIDField", "SmFNode");
            transportationAnalystSetting.put("toNodeIDField", "SmTNode");
            transportationAnalystSetting.put("initFacilityAnalyst", true);//开启设施网络分析
            transportationAnalystSetting.put("directionField", "Direction");//流向字段
            parameter.put("transportationAnalystSetting", transportationAnalystSetting);//发布交通网络分析服务的环境配置类。

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.POST, entity, String.class);
            JSONArray bodyArray = JSON.parseArray(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (bodyArray == null) {
                return RestResponse.fail("未获取到数据！");
            }
            for(int i=0;i<bodyArray.size();i++){
                JSONObject body = bodyArray.getJSONObject(i);
                String serviceAddress = body.getString("serviceAddress");
                String serviceType = body.getString("serviceType");
                if (PlatformObjectUtils.isNotEmpty(serviceAddress) && PlatformObjectUtils.isNotEmpty(serviceType) && serviceType.equals("RESTTRANSPORTATIONANALYST")){
                    networkanalystVersion.setId(UUIDGenerator.getUUID());
                    String networkUrl = serviceAddress + "/networkanalyst/"+dataset+"@"+datasource;
                    networkanalystVersion.setNetworkUrl(networkUrl);
                    //获取新的交通网络分析服务版本号
                    String version = getNetworkanalystVersionCode();
                    networkanalystVersion.setVersion(version);
                    networkanalystVersion.setDelFlag(YNEnum.N.toString());
                    networkanalystVersion.setCreateUser(PlatformSessionUtils.getUserId());
                    String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
                    SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
                    String userName = sUser.getUserName();
                    networkanalystVersion.setCreateUserName(userName);
                    networkanalystVersion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                    //保存交通网络分析服务版本信息
                    saveNetworkanalystVersion(networkanalystVersion);
                    restResponse = RestResponse.succeed("发布成功！");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }

    public String getNetworkanalystVersionCode() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String date = df.format(new Date());
        String version = date+"SSWL";//设施网络分析
        int count = 0;
        try{
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
            String date1 = df1.format(new Date());
            String sql = "select count(*) from sys_networkanalyst_version where version like '%LJGH%' and cast(create_time as varchar) like '%"+date1+"%'";
            count = jdbcTemplate.queryForObject(sql,  Integer.class);
        }catch (Exception e){
            count = 0;
        }
        count++;
        if(count<10){
            version += "000" + count;
        }else if(count<100){
            version += "00" + count;
        }else if(count<1000){
            version += "0" + count;
        }else{
            version += count;
        }
        return version;
    }

    //保存交通网络分析服务版本信息
    public int saveNetworkanalystVersion(NetworkanalystVersion networkanalystVersion){
        String sql = "insert into sys_networkanalyst_version " +
                "(id,smwu_url,udbx_url,datasource,dataset,network_url," +
                "del_flag,create_user,create_user_name,create_time,attach_ids,task_id,direction_field," +
                "data_type,select_version1,select_version2,select_version3,version,remark) " +
                "values (:id,:smwuUrl,:udbxUrl,:datasource,:dataset,:networkUrl," +
                ":delFlag,:createUser,:createUserName,:createTime,:attachIds,:taskId,:directionField," +
                ":dataType,:selectVersion1,:selectVersion2,:selectVersion3,:version,:remark)";
        BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(networkanalystVersion);
        return namedParameterJdbcTemplate.update(sql, source);
    }

    //根据ID逻辑删除版本
    public boolean deleteNetworkanalystVersionById(String id){
        try{
            String sql = "update sys_networkanalyst_version set del_flag ='" + YNEnum.Y.toString() + "' where id='"+id+"'";
            jdbcTemplate.update(sql);

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //删除超图工作空间服务
    private RestResponse supermapDeleteWorkspace(Map<String, Object> map, String serverToken) {
        RestResponse restResponse = null;
        try {
            NetworkanalystVersion networkanalystVersion = (NetworkanalystVersion) map.get("networkanalystVersion");
            String smwuUrl = networkanalystVersion.getSmwuUrl();//工作空间路径
            String udbxUrl = networkanalystVersion.getUdbxUrl();//工作空间路径
            if (PlatformObjectUtils.isEmpty(smwuUrl)){
                return RestResponse.fail("缺少超图工作空间文件参数");
            }
            //删除工作空间服务
//            String dataUrl = iServerHttp + "/iserver/manager/workspaces.rjson?token=" + serverToken;
            String dataUrl = iServerHttp10i + "/iserver/manager/workspaces.rjson?token=" + serverToken;//10i试用版网络分析服务
            try {
                dataUrl = URLDecoder.decode(dataUrl, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return RestResponse.fail(e.getMessage());
            }
            dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
            //System.out.println(dataUrl);

            JSONObject parameter = new JSONObject();
            parameter.put("workspaceConnectionInfo", smwuUrl);//工作空间路径或者数据库的连接信息

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=UTF-8");

            HttpEntity<JSONObject> entity = new HttpEntity<>(parameter, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.PUT, entity, String.class);
            JSONObject body = JSON.parseObject(JSON.parseObject(JSON.toJSONString(exchange)).getString("body"));
            if (body == null) {
                return RestResponse.fail("未获取到数据！");
            }
            boolean bool = body.getBoolean("succeed");
            if (bool){
                restResponse = RestResponse.succeed("删除超图工作空间服务成功！");
            }else{
                restResponse = RestResponse.succeed("删除超图工作空间服务失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        return restResponse;
    }
}

